package com.golte.dataform.analysis.config;

import com.alibaba.fastjson.JSON;

import com.golte.dataform.analysis.common.JwtUtil;
import com.golte.dataform.analysis.vo.request.ReportReq;
import com.golte.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 系统日志，切面处理类
 *
 * @author terry
 */
@Slf4j
@Aspect
@Component
public class DataAspect {
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 切入点，定义所有的控制器
     */
    @Pointcut("execution(public * com.golte.dataform.analysis.controller.ReportController.*(..)))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        //获取上下文request，获取token并解析
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");
        //获取参数并赋值
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            Claims claims = jwtUtil.parseJwt(token);
            Integer roleId = (Integer) claims.get("r");
            if (1 != roleId) {
                //对于不同的Vo类进行相应的赋值
                if (arg instanceof ReportReq) {
                    ReportReq reportReq = (ReportReq) arg;
                    log.info("请求参数before：{}", reportReq);

                    List<Integer> industryIds = (List<Integer>) claims.get("i");
                    List<Integer> brandIds = (List<Integer>) claims.get("b");
                    if (CollectionUtils.isEmpty(reportReq.getIndustryIds())) {
                        reportReq.setIndustryIds(industryIds);
                    } else {
                        reportReq.getIndustryIds().retainAll(industryIds);
                    }
                    if (CollectionUtils.isEmpty(reportReq.getBrandIds())) {
                        reportReq.setBrandIds(brandIds);
                    } else {
                        reportReq.getBrandIds().retainAll(brandIds);
                    }

                }

            }

        }
    }


}
